package cn.terminus.service.customer.settledenterpriseinfo;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.terminus.biz.customer.contractinfo.ContractInfoManager;
import cn.terminus.biz.customer.customcontacts.CustomContactsManager;
import cn.terminus.biz.customer.custominfo.CustomInfoManager;
import cn.terminus.biz.customer.customlabel.CustomLabelManager;
import cn.terminus.biz.customer.settledenterprisebillinfo.SettledEnterpriseBillInfoManager;
import cn.terminus.biz.customer.settledenterpriseinfo.SettledEnterpriseInfoManager;
import cn.terminus.client.customer.analysis.param.SettledEnterpriseAnalysisParam;
import cn.terminus.client.customer.analysis.result.CustomerNatureIndustryResult;
import cn.terminus.client.customer.analysis.result.CustomerNatureIndustryResultList;
import cn.terminus.client.customer.analysis.result.SettledEnterpriseLabelNumResult;
import cn.terminus.client.customer.contractinfo.service.ContractInfoService;
import cn.terminus.client.customer.custompurposeroom.result.CustomPurposeRoomResult;
import cn.terminus.client.customer.settledenterpriseinfo.param.*;
import cn.terminus.client.customer.settledenterpriseinfo.result.SettledEnterpriseInfoResult;
import cn.terminus.client.customer.settledenterpriseinfo.service.SettledEnterpriseInfoService;
import cn.terminus.common.customer.bean.analysis.CustomerNatureIndustryNumResultDto;
import cn.terminus.common.customer.bean.analysis.SettledEnterpriseAnalysisDto;
import cn.terminus.common.customer.bean.analysis.SettledEnterpriseLabelNumResultDto;
import cn.terminus.common.customer.bean.contractinfo.dto.ContractInfoResultDto;
import cn.terminus.common.customer.bean.customcontacts.dto.CustomContactsDeleteDto;
import cn.terminus.common.customer.bean.customcontacts.dto.CustomContactsNewDto;
import cn.terminus.common.customer.bean.custominfo.dto.CustomInfoNewDto;
import cn.terminus.common.customer.bean.customlabel.dto.CustomLabelDeleteDto;
import cn.terminus.common.customer.bean.customlabel.dto.CustomLabelNewDto;
import cn.terminus.common.customer.bean.settledenterprisebillinfo.dto.SettledEnterpriseBillInfoDeleteDto;
import cn.terminus.common.customer.bean.settledenterprisebillinfo.dto.SettledEnterpriseBillInfoNewDto;
import cn.terminus.common.customer.bean.settledenterpriseinfo.dto.*;
import cn.terminus.common.customer.constant.CustomContactsTypeEnum;
import cn.terminus.common.customer.constant.DictCodeConstant;
import cn.terminus.result.common.annotation.TerminusParamVilidator;
import cn.terminus.result.common.context.TerminusCallContext;
import cn.terminus.result.common.exception.DataAccessException;
import cn.terminus.result.common.exception.ServiceException;
import cn.terminus.result.common.page.TerminusPageAble;
import cn.terminus.result.common.page.TerminusPageInfo;
import cn.terminus.result.common.result.TerminusResult;
import cn.terminus.result.common.util.BeanCopyUtils;
import cn.terminus.service.customer.analysis.OverviewAnalysis;
import cn.terminus.service.customer.common.AbstractTerminusService;
import cn.terminus.service.customer.custominfo.CustomInfoServiceImpl;
import cn.terminus.service.customer.feign.carrier.CarrierFeignClient;
import cn.terminus.service.customer.feign.carrier.ProjectRoomDetailResult;
import cn.terminus.service.customer.kafka.KafkaCustomerParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

/**
 * (SettledEnterpriseInfo)表服务实现类
 *
 * @author makejava
 * @since 2021-07-08 11:19:08
 */
@Service
public class SettledEnterpriseInfoServiceImpl extends AbstractTerminusService implements SettledEnterpriseInfoService {
    /**
     * 日志
     */
    protected final Logger logger = LoggerFactory.getLogger(getClass());
    @Resource
    private SettledEnterpriseInfoManager settledEnterpriseInfoManager;
    @Resource
    private CustomContactsManager customContactsManager;
    @Resource
    private CustomLabelManager customLabelManager;
    @Resource
    private SettledEnterpriseBillInfoManager settledEnterpriseBillInfoManager;
    @Resource
    private CustomInfoManager customInfoManager;
    @Resource
    CustomInfoServiceImpl customInfoService;
    @Resource
    private ContractInfoService contractInfoService;
    @Resource
    CarrierFeignClient carrierFeignClient;
    @Resource
    private ContractInfoManager contractInfoManager;

    private final Integer END_NUMBER = 10;
    private final Integer START_NUMBER = 0;


    private Long saveSettledEnterpriseBaseInfo(TerminusCallContext context, AddSettledEnterpriseInfoDto newDto) throws DataAccessException, ServiceException {
        //保存基本信息
        CustomInfoNewDto customInfoNewDto = new CustomInfoNewDto();
        CustomInfoNewDto customInfoNewForm = newDto.getSettledEnterpriseBaseInfo();
        if (!BeanUtil.isEmpty(customInfoNewForm)) {
            checkParam(customInfoNewForm);
            BeanCopyUtils.copyProperties(customInfoNewForm, customInfoNewDto);
            customInfoNewDto.setBusinessId(newDto.getBusinessId());
            customInfoNewDto.setId(newDto.getId());
            customInfoNewDto.setStatus(true);
            //新建的入驻企业招商阶段为合同已签订
            customInfoNewDto.setCboCustomStage(DictCodeConstant.CUSTOMSTAGE3);
            customInfoNewDto.setSettledStatus(true);
            customInfoNewDto.setCreateTime(context.getCallTime());
            customInfoNewDto.setCreateUser(context.getUser().getCallerName());
            customInfoManager.add(customInfoNewDto);
            //保存联系人
            List<CustomContactsNewDto> contactsNewFormList = newDto.getCustomContactsNewList();
            List<CustomContactsNewDto> list = new ArrayList<>();
            if (!CollUtil.isEmpty(contactsNewFormList)) {
                for (CustomContactsNewDto customContactsDto : contactsNewFormList) {
                    CustomContactsNewDto customContactsNewDto = new CustomContactsNewDto();
                    BeanCopyUtils.copyProperties(customContactsDto, customContactsNewDto);
                    customContactsNewDto.setType(CustomContactsTypeEnum.CUSTOMER_MANAGER.getCode());
                    customContactsNewDto.setCboCustomId(newDto.getId());
                    customContactsNewDto.setId(genUUID());
                    customContactsNewDto.setBusinessId(newDto.getBusinessId());
                    customContactsNewDto.setCreateTime(context.getCallTime());
                    customContactsNewDto.setCreateUser(context.getUser().getCallerName());
                    list.add(customContactsNewDto);
                }
                customContactsManager.addMulti(list);
            }
            //保存客户标签
            List<String> customLabel = newDto.getCboCustomLabel();
            List<CustomLabelNewDto> labelNewDtoList = new ArrayList<>();
            if (!CollUtil.isEmpty(customLabel)) {
                for (String lable : customLabel) {
                    CustomLabelNewDto customLabelNewDto = new CustomLabelNewDto();
                    BeanCopyUtils.copyProperties(newDto, customLabelNewDto);
                    customLabelNewDto.setCboCustomLabel(lable);
                    customLabelNewDto.setCboCustomId(newDto.getId());
                    customLabelNewDto.setId(genUUID());
                    customLabelNewDto.setCreateTime(context.getCallTime());
                    customLabelNewDto.setCreateUser(context.getUser().getCallerName());
                    labelNewDtoList.add(customLabelNewDto);
                }
                customLabelManager.addMulti(labelNewDtoList);
            }
            return newDto.getId();
        } else {
            return null;
        }

    }

    private void saveBillInfo(TerminusCallContext context, AddSettledEnterpriseInfoDto newDto) throws DataAccessException {
        SettledEnterpriseBillInfoNewDto settledEnterpriseBillInfoNewDto = new SettledEnterpriseBillInfoNewDto();
        SettledEnterpriseBillInfoNewDto settledEnterpriseBillInfo = newDto.getSettledEnterpriseBillInfo();
        if (!BeanUtil.isEmpty(settledEnterpriseBillInfo)) {
            BeanCopyUtils.copyProperties(settledEnterpriseBillInfo, settledEnterpriseBillInfoNewDto);
            settledEnterpriseBillInfoNewDto.setBusinessId(newDto.getBusinessId());
            settledEnterpriseBillInfoNewDto.setId(genUUID());
            settledEnterpriseBillInfoNewDto.setCboSettledEnterpriseId(newDto.getId());
            settledEnterpriseBillInfoNewDto.setCreateTime(context.getCallTime());
            settledEnterpriseBillInfoNewDto.setCreateUser(context.getUser().getCallerName());
            settledEnterpriseBillInfoManager.add(settledEnterpriseBillInfoNewDto);
        }
    }

//    private void saveBussinessInfo(TerminusCallContext context, AddSettledEnterpriseInfoDto newDto) throws DataAccessException {
//        CustomBusinessInfoNewDto customBusinessInfoNewDto = new CustomBusinessInfoNewDto();
//        CustomBusinessInfoNewDto customBusinessInfo = newDto.getCustomBusinessInfo();
//        if (!BeanUtil.isEmpty(customBusinessInfo)) {
//            BeanCopyUtils.copyProperties(customBusinessInfo, customBusinessInfoNewDto);
//            customBusinessInfoNewDto.setType(TypeEnum.SETTLED_ENTERPRISE_MANAGER.getCode());
//            customBusinessInfoNewDto.setBusinessId(newDto.getBusinessId());
//            customBusinessInfoNewDto.setId(genUUID());
//            customBusinessInfoNewDto.setCreateTime(context.getCallTime());
//            customBusinessInfoNewDto.setCreateUser(context.getUser().getCallerName());
//            customBusinessInfoManager.add(customBusinessInfoNewDto);
//
//            CustomBusinessNewDto customBusinessNewDto = new CustomBusinessNewDto();
//            BeanCopyUtils.copyProperties(newDto, customBusinessNewDto);
//            customBusinessNewDto.setId(genUUID());
//            customBusinessNewDto.setCboCustomId(newDto.getId());
//            customBusinessNewDto.setCboCustomBusinessId(customBusinessInfoNewDto.getId());
//            customBusinessNewDto.setCreateTime(context.getCallTime());
//            customBusinessNewDto.setCreateUser(context.getUser().getCallerName());
//            customBusinessManager.add(customBusinessNewDto);
//        }
//    }


    public void checkParam(CustomInfoNewDto customInfoNewForm) throws ServiceException, DataAccessException {
        if (StrUtil.isEmpty(customInfoNewForm.getCboCustomName())) {
            throw new ServiceException("410016", this.getMessage("410016"));
        }
    }


    /**
     * 新增
     *
     * @param param
     * @param context
     * @return
     * @throws ServiceException
     */
    @Override
    @TerminusParamVilidator(argsIndexs = {0, 1})
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public TerminusResult<String> add(AddSettledEnterpriseInfoParam param, TerminusCallContext context) throws ServiceException {
        AddSettledEnterpriseInfoDto newDto = new AddSettledEnterpriseInfoDto();
        BeanCopyUtils.queryCopyProperties(param, context, newDto);
        try {
            //客户管理中已存在，改变settledStatus状态
            if (newDto.getCboCustomerId() != null) {
                newDto.setId(newDto.getCboCustomerId());
                settledEnterpriseInfoManager.updateSettledStatus(newDto.getCboCustomerId());
                settledEnterpriseInfoManager.updateStage(newDto.getCboCustomerId());
                //保存开票信息
                saveBillInfo(context, newDto);
                //保存工商信息暂不开发
                //saveBussinessInfo(context,newDto);

                //发送概览kafka
                this.sendOverviewKafka(new OverviewAnalysis(context, null, 1));
                return TerminusResult.success(String.valueOf(newDto.getCboCustomerId()));
            } else { //否则保存基本信息至客户表中
                newDto.setId(genUUID());
                //保存开票信息
                saveBillInfo(context, newDto);
                //保存工商信息暂不开发
                //saveBussinessInfo(context,newDto);
                //保存基本信息

                if (customInfoService.queryByCustomName(newDto.getSettledEnterpriseBaseInfo().getCboCustomName(), context) != null) {
                    return TerminusResult.fail("410015", this.getMessage("410015"));
                }
                Long id = saveSettledEnterpriseBaseInfo(context, newDto);
                if (id == null || id < 1) {
                    return TerminusResult.fail("410001", this.getMessage("410001"));
                }

                //发送概览kafka
                this.sendOverviewKafka(new OverviewAnalysis(context, 1, 1));
                CompletableFuture.runAsync(() -> {
                    //发送客户管理kafka
                    this.sendCustomerKafka(KafkaCustomerParam.setCustomerMessage(context, newDto.getSettledEnterpriseBaseInfo().getCboCustomIndustry(), newDto.getSettledEnterpriseBaseInfo().getCboCustomNature(), 1));
                });
                return TerminusResult.success(String.valueOf(newDto.getId()));
            }

        } catch (Exception e) {
            logger.error("新增失败,错误信息：{}", e.getMessage());
            throw new ServiceException(e);
        }

    }

    /**
     * 更新
     *
     * @param param
     * @param context
     * @return
     * @throws ServiceException
     */
    @Override
    @TerminusParamVilidator(argsIndexs = {0, 1})
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public TerminusResult<Boolean> update(SettledEnterpriseInfoEditParam param, TerminusCallContext context) throws ServiceException {
        SettledEnterpriseInfoEditDto editDto = new SettledEnterpriseInfoEditDto();
        BeanCopyUtils.queryCopyProperties(param, context, editDto);
        try {
            //修改原企业的基本信息
            if (editDto.getId() != null && editDto.getCboCustomerId() != null && editDto.getId().longValue() == editDto.getCboCustomerId().longValue()) {
                updateSettledEnterpriseInfo(editDto, context);
            } else if (editDto.getId() != null && editDto.getCboCustomerId() == null) {
                //新增入驻企业并更改原企业状态为非入驻企业
                AddSettledEnterpriseInfoParam addParam = new AddSettledEnterpriseInfoParam();
                BeanCopyUtils.copyProperties(editDto, addParam);
                add(addParam, context);
                settledEnterpriseInfoManager.updateSettledStatusToCustomer(Arrays.asList(editDto.getId()));
            } else if (editDto.getId() != null && editDto.getCboCustomerId() != null && editDto.getId().longValue() != editDto.getCboCustomerId().longValue()) {
                //更改原企业状态为非入驻企业
                settledEnterpriseInfoManager.updateSettledStatusToCustomer(Arrays.asList(editDto.getId()));
                //并修改新入驻企业状态
                settledEnterpriseInfoManager.updateSettledStatus(editDto.getCboCustomerId());
                //新增开票信息(删除之前开票信息)
                AddSettledEnterpriseInfoDto newDto = new AddSettledEnterpriseInfoDto();
                BeanCopyUtils.copyProperties(editDto, newDto);
                newDto.setId(editDto.getCboCustomerId());
                SettledEnterpriseBillInfoDeleteDto deleteDto = new SettledEnterpriseBillInfoDeleteDto();
                List<Long> list = new ArrayList<>();
                list.add(editDto.getCboCustomerId());
                deleteDto.setIds(list);
                settledEnterpriseBillInfoManager.delete(deleteDto);
                saveBillInfo(context, newDto);
            }

        } catch (DataAccessException e) {
            logger.error("更新失败,错误信息：{}", e.getMessage());
            throw new ServiceException(e);
        }
        return TerminusResult.success(true);
    }

    public void updateSettledEnterpriseInfo(SettledEnterpriseInfoEditDto editDto, TerminusCallContext context) throws DataAccessException {
        //修改基本信息
        if (!BeanUtil.isEmpty(editDto.getSettledEnterpriseBaseInfo())) {
            editDto.getSettledEnterpriseBaseInfo().setId(editDto.getId());
            editDto.getSettledEnterpriseBaseInfo().setBusinessId(editDto.getBusinessId());
            editDto.getSettledEnterpriseBaseInfo().setLastUpdateTime(context.getCallTime());
            editDto.getSettledEnterpriseBaseInfo().setLastUpdateUser(context.getUser().getCallerName());
            customInfoManager.update(editDto.getSettledEnterpriseBaseInfo());
        }
        //修改标签信息
        List<String> cboCustomLabel = editDto.getCboCustomLabel();
        List<CustomLabelNewDto> labelNewDtoList = new ArrayList<>();
        //不传标签字段则为null,不更改
        CustomLabelDeleteDto deleteDto = new CustomLabelDeleteDto();
        deleteDto.setCboCustomId(editDto.getId());
        customLabelManager.delete(deleteDto);
        if (!BeanUtil.isEmpty(cboCustomLabel)) {
            for (String lable : cboCustomLabel) {
                CustomLabelNewDto customLabelNewDto = new CustomLabelNewDto();
                BeanCopyUtils.copyProperties(editDto, customLabelNewDto);
                customLabelNewDto.setCboCustomLabel(lable);
                customLabelNewDto.setCboCustomId(editDto.getId());
                customLabelNewDto.setId(genUUID());
                customLabelNewDto.setLastUpdateTime(context.getCallTime());
                customLabelNewDto.setLastUpdateUser(context.getUser().getCallerName());
                labelNewDtoList.add(customLabelNewDto);
            }
            //置空判断
            if (!CollUtil.isEmpty(labelNewDtoList)) {
                customLabelManager.addMulti(labelNewDtoList);
            }
        }
        //修改联系人
        CustomContactsDeleteDto customContactsDeleteDto = new CustomContactsDeleteDto();
        customContactsDeleteDto.setCboCustomId(editDto.getId());
        customContactsManager.delete(customContactsDeleteDto);
        List<CustomContactsNewDto> customContactsList = editDto.getCustomContactsNewList();
        List<CustomContactsNewDto> customContactsNewList = new ArrayList<>();
        if (!BeanUtil.isEmpty(customContactsList)) {
            for (CustomContactsNewDto customContactsDto : customContactsList) {
                CustomContactsNewDto customContactsNewDto = new CustomContactsNewDto();
                BeanCopyUtils.copyProperties(customContactsDto, customContactsNewDto);
                customContactsNewDto.setType(CustomContactsTypeEnum.CUSTOMER_MANAGER.getCode());
                customContactsNewDto.setCboCustomId(editDto.getId());
                customContactsNewDto.setId(genUUID());
                customContactsNewDto.setBusinessId(editDto.getBusinessId());
                customContactsNewDto.setLastUpdateTime(context.getCallTime());
                customContactsNewDto.setLastUpdateUser(context.getUser().getCallerName());
                customContactsNewList.add(customContactsNewDto);
            }
            if (!CollUtil.isEmpty(customContactsNewList)) {
                customContactsManager.addMulti(customContactsNewList);
            }
        }

        //删除开票信息
        SettledEnterpriseBillInfoDeleteDto settledEnterpriseBillInfoDeleteDto = new SettledEnterpriseBillInfoDeleteDto();
        List<Long> ids = Arrays.asList(editDto.getId());
        settledEnterpriseBillInfoDeleteDto.setIds(ids);
        settledEnterpriseBillInfoManager.delete(settledEnterpriseBillInfoDeleteDto);
        SettledEnterpriseBillInfoNewDto settledEnterpriseBillInfo = editDto.getSettledEnterpriseBillInfo();
        if (!BeanUtil.isEmpty(settledEnterpriseBillInfo)) {
            SettledEnterpriseBillInfoNewDto settledEnterpriseBillInfoNewDto = new SettledEnterpriseBillInfoNewDto();
            BeanCopyUtils.copyProperties(settledEnterpriseBillInfo, settledEnterpriseBillInfoNewDto);
            settledEnterpriseBillInfoNewDto.setCboSettledEnterpriseId(editDto.getId());
            settledEnterpriseBillInfoNewDto.setId(genUUID());
            //新增开票信息
            settledEnterpriseBillInfoManager.add(settledEnterpriseBillInfoNewDto);
        }
    }

    /**
     * 删除
     *
     * @param param
     * @param context
     * @return
     * @throws ServiceException
     */
    @Override
    @TerminusParamVilidator(argsIndexs = {0, 1})
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public TerminusResult<Boolean> delete(SettledEnterpriseInfoDeleteParam param, TerminusCallContext context) throws ServiceException {
        SettledEnterpriseInfoDeleteDto deleteDto = new SettledEnterpriseInfoDeleteDto();
        BeanCopyUtils.queryCopyProperties(param, context, deleteDto);
        try {
            Integer countNum = contractInfoManager.getByCustomerIdList(deleteDto.getIds());
            if (countNum > 0) {
                return TerminusResult.fail("410018", this.getMessage("410018"));
            }
            settledEnterpriseInfoManager.updateSettledStatusToCustomer(deleteDto.getIds());
            //发送概览kafka
            this.sendOverviewKafka(new OverviewAnalysis(context, null, -deleteDto.getIds().size()));
        } catch (DataAccessException e) {
            logger.error("删除失败,错误信息：{}", e.getMessage());
            throw new ServiceException(e);
        }
        return TerminusResult.success(true);
    }


    /**
     * 查询
     *
     * @param param
     * @param context
     * @return
     * @throws ServiceException
     */
    @Override
    @TerminusParamVilidator(argsIndexs = {0, 1})
    public TerminusResult<SettledEnterpriseInfoResult> gets(SettledEnterpriseInfoGetsParam param, TerminusCallContext context) throws ServiceException {
        SettledEnterpriseInfoGetsDto getsDto = new SettledEnterpriseInfoGetsDto();
        BeanCopyUtils.queryCopyProperties(param, context, getsDto);
        try {
            SettledEnterpriseInfoResultDto getsResultList = settledEnterpriseInfoManager.gets(getsDto);
            if (BeanUtil.isEmpty(getsResultList)) {
                return null;
            }

            List<String> projectRoomStringList = new ArrayList<>();
            List<String> finalProjectRoomStringList = projectRoomStringList;
            List<Long> roomIdList = new ArrayList<>();
            List<ProjectRoomDetailResult> projectRoomDetailResultList = new ArrayList<>();
            List<CustomPurposeRoomResult> customPurposeRoomResultList = new ArrayList<>();
            //合同信息
            List<ContractInfoResultDto> contractInfoList = getsResultList.getContractInfoResultList();
            List<ContractInfoResultDto> contractInfoNewList = new ArrayList<>();

            if (!CollUtil.isEmpty(contractInfoList)) {
                //截取10条
                List<ContractInfoResultDto> contractInfoListTen = contractInfoList.subList(START_NUMBER, contractInfoList.size() > END_NUMBER ? END_NUMBER : contractInfoList.size());
                //根据合同查对应房源信息
                List<Long> contractIdList = contractInfoListTen.stream().map(e -> e.getId()).collect(Collectors.toList());
                List<CustomPurposeRoomResult> purposeRoomList = contractInfoService.geturposeRoomInfoByContractIds(contractIdList).getData();
                if (!CollUtil.isEmpty(purposeRoomList)) {
                    roomIdList = purposeRoomList.stream().map(e -> e.getCboRoomId()).collect(Collectors.toList());
                    projectRoomDetailResultList = carrierFeignClient.getDetailByIds(roomIdList).getData();
                }
                List<ProjectRoomDetailResult> finalProjectRoomDetailResultList = projectRoomDetailResultList;
                customPurposeRoomResultList = purposeRoomList.stream().map(e -> {
                    if (!CollUtil.isEmpty(finalProjectRoomDetailResultList)) {
                        for (ProjectRoomDetailResult projectRoomDetailResult : finalProjectRoomDetailResultList) {
                            if (projectRoomDetailResult.getId().longValue() == e.getCboRoomId().longValue()) {
                                e.setCboProjectName(projectRoomDetailResult.getProjectName());
                                e.setCboProjectBuildFloorName(projectRoomDetailResult.getBuildFloorName());
                                e.setCboProjectBuildName(projectRoomDetailResult.getBuildName());
                                e.setCboRoomNo(projectRoomDetailResult.getCboRoomNo());
                                e.setCboArea(projectRoomDetailResult.getCboArea());
                            }
                        }
                    }
                    return e;
                }).collect(Collectors.toList());

                List<CustomPurposeRoomResult> finalCustomPurposeRoomResultList1 = customPurposeRoomResultList;

                for (ContractInfoResultDto contractInfoResultDto : contractInfoListTen) {
                    List<String> purposeRooomStr = new ArrayList();
                    BigDecimal countArea = new BigDecimal(0);
                    if (!CollUtil.isEmpty(finalCustomPurposeRoomResultList1)) {
                        for (CustomPurposeRoomResult customPurposeRoomResult : finalCustomPurposeRoomResultList1) {
                            if (contractInfoResultDto.getId().longValue() == customPurposeRoomResult.getContractId()) {
                                if (customPurposeRoomResult.getCboProjectName() != null) {
                                    String join = String.join(",", customPurposeRoomResult.getCboProjectName(),
                                            customPurposeRoomResult.getCboProjectBuildName() + customPurposeRoomResult.getCboProjectBuildFloorName() + customPurposeRoomResult.getCboRoomNo());
                                    purposeRooomStr.add(join);
                                }
                                if (customPurposeRoomResult.getCboArea() != null && countArea != null) {
                                    countArea = customPurposeRoomResult.getCboArea().add(countArea);
                                }
                            }
                        }
                        contractInfoResultDto.setPurposeRoomStr(purposeRooomStr);
                        contractInfoResultDto.setCboArea(countArea);
                    }
                    contractInfoNewList.add(contractInfoResultDto);
                }

                getsResultList.setContractInfoResultList(contractInfoNewList);
                return TerminusResult.success(BeanCopyUtils.copyProperties(getsResultList, SettledEnterpriseInfoResult.class));
            }
            return TerminusResult.success(BeanCopyUtils.copyProperties(getsResultList, SettledEnterpriseInfoResult.class));
        } catch (DataAccessException e) {
            logger.error("查询失败,错误信息：{}", e.getMessage());
            throw new ServiceException(e);
        }
    }

    /**
     * 分页查询
     *
     * @param param
     * @param context
     * @return
     * @throws ServiceException
     */
    @Override
    @TerminusParamVilidator(argsIndexs = {0, 1})
    public TerminusResult<TerminusPageAble<SettledEnterpriseInfoResult>> page(SettledEnterpriseInfoQueryParam param, TerminusPageInfo page, TerminusCallContext context) throws ServiceException {
        SettledEnterpriseInfoQueryDto queryDto = new SettledEnterpriseInfoQueryDto();
        BeanCopyUtils.queryCopyProperties(param, context, queryDto);
        try {
            if (!BeanUtil.isEmpty(queryDto.getEndTime())) {
                Calendar instance = Calendar.getInstance();
                instance.setTime(queryDto.getEndTime());
                instance.add(Calendar.HOUR, 23);
                instance.add(Calendar.MINUTE, 59);
                instance.add(Calendar.SECOND, 59);
                queryDto.setEndTime(instance.getTime());
            }
            if (!BeanUtil.isEmpty(queryDto.getFollowEndTime())) {
                Calendar instance = Calendar.getInstance();
                instance.setTime(queryDto.getFollowEndTime());
                instance.add(Calendar.HOUR, 23);
                instance.add(Calendar.MINUTE, 59);
                instance.add(Calendar.SECOND, 59);
                queryDto.setFollowEndTime(instance.getTime());
            }
            TerminusPageAble<SettledEnterpriseInfoResultDto> TerminusPageAble = settledEnterpriseInfoManager.page(queryDto, page);
            Collection<SettledEnterpriseInfoResultDto> datas = TerminusPageAble.getDatas();
            if (CollectionUtils.isEmpty(datas)) {
                return TerminusResult.success(new TerminusPageAble<>(new ArrayList<>(), page, 0));
            }
            List<SettledEnterpriseInfoResultDto> list = BeanCopyUtils.copy(datas, SettledEnterpriseInfoResultDto.class);
            list.stream().map(e -> {
                List<ContractInfoResultDto> contractInfoResultList = e.getContractInfoResultList();
                if (contractInfoResultList.size() > END_NUMBER) {
                    contractInfoResultList = contractInfoResultList.subList(START_NUMBER, contractInfoResultList.size() > END_NUMBER ? END_NUMBER : contractInfoResultList.size());
                }
                e.setContractInfoResultList(contractInfoResultList);
                return e;
            }).collect(Collectors.toList());
            transferDictCodeToName(list);
            return TerminusResult.success(new TerminusPageAble<>(BeanCopyUtils.copy(list, SettledEnterpriseInfoResult.class),
                    page, TerminusPageAble.getTotalRows()));
        } catch (DataAccessException e) {
            logger.error("分页查询失败,错误信息：{}", e.getMessage());
            throw new ServiceException(e);
        }

    }

    public void transferDictCodeToName(List<SettledEnterpriseInfoResultDto> list) {
        Map<String, String> channelNameDict = customInfoService.getAllChannelName(DictCodeConstant.CHANNELSOURCE);
        Map<String, String> channelSourceDict = customInfoService.getDictByDictCode(DictCodeConstant.CHANNELSOURCE);
        Map<String, String> customIndustryDict = customInfoService.getDictByDictCode(DictCodeConstant.CUSTOMINDUSTRY);
        Map<String, String> customNatureDict = customInfoService.getDictByDictCode(DictCodeConstant.CUSTOMNATURE);
        //字典值code转换为name返回
        list.stream().forEach(info -> {
            // 渠道名称字典code->name
            if (channelNameDict != null && channelNameDict.size() > 0) {
                String channelName = channelNameDict.get(info.getCboChannelName());
                if (channelName != null) {
                    info.setCboChannelName(channelName);
                }
            }
            //渠道来源code->name
            if (channelSourceDict != null && channelSourceDict.size() > 0) {
                String channelSource = channelSourceDict.get(info.getCboChannelSource());
                if (channelSource != null) {
                    info.setCboChannelSource(channelSource);
                }
            }
            //客户行业code->name
            if (customIndustryDict != null && customIndustryDict.size() > 0) {
                String customIndustry = customIndustryDict.get(info.getCboCustomIndustry());
                if (customIndustry != null) {
                    info.setCboCustomIndustry(customIndustry);
                }
            }

            //客户类型code->name
            if (customNatureDict != null && customNatureDict.size() > 0) {
                String customNature = customNatureDict.get(info.getCboCustomNature());
                if (customNature != null) {
                    info.setCboCustomNature(customNature);
                }
            }
        });
    }


    @Override
    public TerminusResult<CustomerNatureIndustryResultList> analysisSettledEnterpriseWithContract(SettledEnterpriseAnalysisParam param, TerminusCallContext context) throws ServiceException {
        SettledEnterpriseAnalysisDto dto = new SettledEnterpriseAnalysisDto();
        BeanCopyUtils.queryCopyProperties(param, context, dto);
        try {
            CustomerNatureIndustryResultList resultList = new CustomerNatureIndustryResultList();
            List<CustomerNatureIndustryNumResultDto> analysisNatureList = settledEnterpriseInfoManager.analysisSettledEnterpriseNature(dto);
            analysisNatureList = analysisNatureList.stream().sorted(Comparator.comparing(CustomerNatureIndustryNumResultDto::getCustomerNature, (o1, o2) -> o1 == null ? 1 : (o2 == null ? -1 : o2.compareTo(o1)))).collect(Collectors.toList());

            List<CustomerNatureIndustryNumResultDto> analysisIndustryList = settledEnterpriseInfoManager.analysisSettledEnterpriseIndustry(dto);
            analysisIndustryList = analysisIndustryList.stream().sorted(Comparator.comparing(CustomerNatureIndustryNumResultDto::getCustomerIndustry, (o1, o2) -> o1 == null ? 1 : (o2 == null ? -1 : o2.compareTo(o1)))).collect(Collectors.toList());

            customInfoService.analysisNatureAndIndustryDictCodeToName(analysisNatureList, analysisIndustryList);

            resultList.setAnalysisIndustryList(BeanCopyUtils.copy(analysisIndustryList, CustomerNatureIndustryResult.class));
            resultList.setAnalysisNatureList(BeanCopyUtils.copy(analysisNatureList, CustomerNatureIndustryResult.class));
            return TerminusResult.success(resultList);
        } catch (DataAccessException e) {
            logger.error("入驻企业统计分析失败,错误信息：{}", e.getMessage());
            throw new ServiceException(e);
        }

    }

    @Override
    public TerminusResult<List<SettledEnterpriseLabelNumResult>> analysisSettledEnterpriseLabel(SettledEnterpriseAnalysisParam param, TerminusCallContext context) throws ServiceException {
        SettledEnterpriseAnalysisDto dto = new SettledEnterpriseAnalysisDto();
        BeanCopyUtils.queryCopyProperties(param, context, dto);
        try {
            List<SettledEnterpriseLabelNumResultDto> resultList = settledEnterpriseInfoManager.analysisSettledEnterpriseLabel(dto);

            Map<String, String> customLabelDict = customInfoService.getDictByDictCode(DictCodeConstant.CUSTOMLABEL);
            resultList.stream().forEach(info -> {
                //客户性质code->name
                if (customLabelDict != null && customLabelDict.size() > 0) {
                    String customLabel = customLabelDict.get(info.getLabel());
                    if (customLabel != null) {
                        info.setLabel(customLabel);
                    }
                }
            });
            return TerminusResult.success(BeanCopyUtils.copy(resultList, SettledEnterpriseLabelNumResult.class));
        } catch (DataAccessException e) {
            logger.error("签订合同入驻企业标签分类统计失败,错误信息：{}", e.getMessage());
            throw new ServiceException(e);
        }
    }


}


